package com.fll.server;

import com.fll.common.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.io.*;
import java.net.URL;
import java.security.*;
import java.security.cert.CertificateException;

/**
 * @author fanlei
 * @version 1.0
 * @date 2019年01月25日
 */
public class SslContextCreator {
    private static Logger logger = LoggerFactory.getLogger(SslContextCreator.class);

    public SslContextCreator() {
    }

    public SSLContext initSSLContext() {
        logger.info("Checking SSL configuration properties...");
        String jksPath = Config.getInstance().getStringValue("server.ssl.jksPath");
        logger.info("Initializing SSL context. KeystorePath = {}.", jksPath);
        if (jksPath != null && !jksPath.isEmpty()) {
            String keyStorePassword = Config.getInstance().getStringValue("server.ssl.keyStorePassword");
            String keyManagerPassword = Config.getInstance().getStringValue("server.ssl.keyManagerPassword");
            if (keyStorePassword != null && !keyStorePassword.isEmpty()) {
                if (keyManagerPassword != null && !keyManagerPassword.isEmpty()) {
                    boolean needsClientAuth = Config.getInstance().getBooleanValue("server.ssl.needsClientAuth", false);

                    try {
                        logger.info("Loading keystore. KeystorePath = {}.", jksPath);
                        InputStream jksInputStream = this.jksDatastore(jksPath);
                        SSLContext serverContext = SSLContext.getInstance("TLS");
                        KeyStore ks = KeyStore.getInstance("JKS");
                        ks.load(jksInputStream, keyStorePassword.toCharArray());
                        logger.info("Initializing key manager...");
                        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                        kmf.init(ks, keyManagerPassword.toCharArray());
                        TrustManager[] trustManagers = null;
                        if (needsClientAuth) {
                            logger.warn("Client authentication is enabled. The keystore will be used as a truststore. KeystorePath = {}.", jksPath);
                            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                            tmf.init(ks);
                            trustManagers = tmf.getTrustManagers();
                        }

                        logger.info("Initializing SSL context...");
                        serverContext.init(kmf.getKeyManagers(), trustManagers, (SecureRandom)null);
                        logger.info("The SSL context has been initialized successfully.");
                        return serverContext;
                    } catch (UnrecoverableKeyException | CertificateException | KeyStoreException | KeyManagementException | IOException | NoSuchAlgorithmException var11) {
                        logger.error("Unable to initialize SSL context. Cause = {}, errorMessage = {}.", var11.getCause(), var11.getMessage());
                        return null;
                    }
                } else {
                    logger.warn("The key manager password is null or empty. The SSL context won't be initialized.");
                    return null;
                }
            } else {
                logger.warn("The keystore password is null or empty. The SSL context won't be initialized.");
                return null;
            }
        } else {
            logger.warn("The keystore path is null or empty. The SSL context won't be initialized.");
            return null;
        }
    }

    private InputStream jksDatastore(String jksPath) throws FileNotFoundException {
        URL jksUrl = this.getClass().getClassLoader().getResource(jksPath);
        if (jksUrl != null) {
            logger.info("Starting with jks at {}, jks normal {}", jksUrl.toExternalForm(), jksUrl);
            return this.getClass().getClassLoader().getResourceAsStream(jksPath);
        } else {
            logger.warn("No keystore has been found in the bundled resources. Scanning filesystem...");
            File jksFile = new File(jksPath);
            if (jksFile.exists()) {
                logger.info("Loading external keystore. Url = {}.", jksFile.getAbsolutePath());
                return new FileInputStream(jksFile);
            } else {
                logger.warn("The keystore file does not exist. Url = {}.", jksFile.getAbsolutePath());
                return null;
            }
        }
    }
}
